<?php

/**
 * @author      :   Thai Xuan Lam
 * @name        :   Fpt_Plugin_Env
 * @version     :   201108
 * @copyright   :   FPT Online
 * @todo        :   Environment plugin
 */
class Fpt_Plugin_Env extends Zend_Controller_Plugin_Abstract
{
    //Debug mode
    private $debug = 0;
    //Xhp mode
    private $xhp = 0;
    /**
     * Called before Zend_Controller_Front calls on the router
     * to evaluate the request against the registered routes.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        //Get debug
        $this->debug = $request->getParam('vnedtt');
        $this->xhp = $request->getParam('vnextt');

        //Check xhp
        if ($this->xhp)
        {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        }
    }

    /**
     * Called after the router finishes routing the request.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {

    }

    /**
     * Called before Zend_Controller_Front enters its dispatch loop.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        //Get module
        $module = strtolower($request->getModuleName());

        //Get controller
        $controller = strtolower($request->getParam('controller'));

        //Get action
        $action = strtolower($request->getParam('action'));

        //Session namespace
        $session = new Zend_Session_Namespace(SESSION_NAMESPACE);

        //Get userLogin
        $intUserId = Fpt_Sso::checkLoginClient();

        if ( !isset($session->userid) )
        {
            $session->userid = 0;
        }//end if

        //Check login
        if ($intUserId > 0 && $session->userid != $intUserId)
        {
            if ( isset($_SESSION['userOpenID']) )
            {
                //Unset session openid
                unset($_SESSION['userOpenID']);
                //Clean auth openid
                $authOpenId = Zend_Auth::getInstance();
                $authOpenId->clearIdentity();
            }//end if
            
            //Set session UserId
            $session->userid = $intUserId;
            try
            {
                //Init Oauth
                $oauthDirect = Fpt_Global::getDirectOauth();
                $arrToken = $oauthDirect->accessTokenId(array('userid' => $intUserId, 'Auth' => $_COOKIE['Auth']));
                $arrToken = Zend_Json::decode($arrToken);

                if (!empty($arrToken) && $arrToken['response']['error'] == 0)
                {
                    //Set session
                    $_SESSION['authorize'] = $arrToken['response']['result'];

                    //Init Oauth
                    Fpt_Global::getUserLoginOauth();
                    //unset Session auth
                    unset($_SESSION['authorize']);

                    $userInfo = Zend_Json::decode($oauthDirect->execUserByMethodGetUserID(array('userid'=>Zend_Json::encode(array($intUserId)),'viewid'=>$intUserId)));

                    if(!is_array($userInfo) || !is_array($userInfo['response'])  || $userInfo['response']['error'] > 0  || empty($userInfo['response']['result']))
                    {
                        $session->userid = 0;
                    }
                    else
                    {
                        $session->user = array(
                                'userid'        => $userInfo['response']['result'][$intUserId]['userid'],
                                'displayname'   => $userInfo['response']['result'][$intUserId]['firstname'],
                                'email'         => $userInfo['response']['result'][$intUserId]['email'],
                                'avatar'        => $userInfo['response']['result'][$intUserId]['avatar'],
                                'url'           => $userInfo['response']['result'][$intUserId]['url'],
                                'fullname'      => $userInfo['response']['result'][$intUserId]['fullname'],
                                'firstname'     => $userInfo['response']['result'][$intUserId]['firstname'],
                                'lastname'      => $userInfo['response']['result'][$intUserId]['lastname']
                        );
                    }
                }

            }
            catch(Exception $e)
            {
                $session->userid = 0;
            }//end try catch
        }
        elseif ( !$intUserId || $intUserId<0 )
        {
            unset($session->user);
            unset($session->userid);
        }//end if

        //Setup Include Paths
        set_include_path(implode(PATH_SEPARATOR, array(
                APPLICATION_PATH . '/modules/' . $module . '/models',
                get_include_path()
        )));
        
        //Check module clbtoiyeu
        if ( in_array($module, array('clbtoiyeu')) )
        {
            //Set session for fckinser
            if ( $intUserId > 0 )
            {
                $_SESSION['userclbtoiyeu']  = 1;
            }
            else
            {
                $session->userid    = 0;
                $session->user      = array(
                        'userid'    => '-1',
                        'fullname'  => '',
                        'firstname' => '',
                        'lastname'  => '',
                        'email'     => '',
                        'avatar'    => '',
                        'url'       => ''
                );
                unset($_SESSION['userclbtoiyeu']);
            }//end if

            //Layout setup
            $layoutInstance = Zend_Layout::startMvc(
                    array(
                    'layout'        => 'layout',
                    'layoutPath'    => APPLICATION_PATH.'/layouts/clbtoiyeu/scripts',
                    'contentKey'    => 'content'
                    )
            );

            //Get current view
            $viewInstance = $layoutInstance->getView();

            //Add view phtml
            $viewInstance->addHelperPath(APPLICATION_PATH.'/layouts/clbtoiyeu/helpers');

            //Assign to view
            $viewInstance->user = $session->user;

            //Cleanup data
            unset($layoutInstance, $viewInstance);
        }
        //Check module euro2012
        elseif ( in_array($module, array('euro2012')) )
        {
            //Setup Include Paths
            set_include_path(implode(PATH_SEPARATOR, array(
                    APPLICATION_PATH . '/modules/default/models',
                    get_include_path()
            )));

            //Set parent params
            Zend_Registry::set(PARENT_PARAMS_CONFIG, $request->getParams());
            
            //Process mvc block
            Fpt_Plugin_Block::processBlockMvc($this->_request->getParam('cateid', CATE_EURO_ID), $module, $controller, $action);

            //Get layout
            $layoutName = Fpt_Plugin_Block::getLayouts();
            $layoutName = str_replace('.phtml', '', $layoutName);

            //Layout setup
            $layoutInstance = Zend_Layout::startMvc(
                    array(
                    'layout' => (!empty($layoutName))?$layoutName:'default',
                    'layoutPath' => APPLICATION_PATH . '/layouts/euro2012/scripts/',
                    'contentKey' => 'content'
                    )
            );

            //Get current view
            $viewInstance = $layoutInstance->getView();

            //Add view phtml
            $viewInstance->addHelperPath(APPLICATION_PATH.'/layouts/helpers');

            //Assign to view
            $viewInstance->userid = $session->userid;
            $viewInstance->user = $session->user;
			
			//Get application configuration
            $configuration = Fpt_Global::getApplicationIni();
			$viewInstance->config = $configuration['app'];
            //echo "<pre>"; print_r($configuration['images']); die;
            $viewInstance->imageSize = $configuration['images'];

            // Load data for top menu
            $arrListAllCategory = Category::getInstance()->getMenu();
            
            $arrMenu = array();

            if(!empty($arrListAllCategory))
            {
                $arrMenu = $arrListAllCategory[CATE_EURO_ID];
            }

            $viewInstance->arrMenu = $arrMenu['child'];
            
            // Load data for Team
            $arrTeamByTable = TeamSeason::getInstance()->getRankingEuro2012(SEASON_ID, LEAGUE_ID, null);
            $viewInstance->arrTableMatch = $arrTeamByTable;

            if(!empty($layoutName))
            {
                //Execute all sections in layout
                Fpt_Plugin_Block::processSections();
            }

            //Cleanup data
            unset($layoutInstance, $viewInstance);
        }
        else
        {
            //Parser params
            if(in_array($controller, array('cate', 'video', 'fixture', 'ranking')))
            {
                $category = Category::getInstance();
                if($this->_request->getParam('catecode'))
                {
                    $catename = $this->_request->getParam('catecode');
                }
                else
                {
                    $catename = explode('/', $this->_request->getParam('catename'));
                    if(count($catename)<=2)
                    {
                        if(count($catename)==2)
                        {
                            $cateInfo = $category->getCategoryByCode($catename[0]);
                            $this->_request->setParam('pcateid', $cateInfo['category_id']);
                        }
                        $catename = end($catename);
                    }
                    else
                    {
                        $pageIdx = array_search('page', $catename);
                        $page = (isset($catename[$pageIdx+1]))?(int)$catename[$pageIdx+1]:1;
                        $catename = (isset($catename[$pageIdx-1]))?$catename[$pageIdx-1]:'';
                        $this->_request->setParam('page', $page);
                    }
                }
                $cateInfo = $category->getCategoryByCode($catename);
                if($cateInfo)
                {
                    $this->_request->setParam('cateid', $cateInfo['category_id']);
                }
            }
            //Set parent params
            Zend_Registry::set(PARENT_PARAMS_CONFIG, $request->getParams());

            //Process mvc block
            Fpt_Plugin_Block::processBlockMvc($this->_request->getParam('cateid', 0), $module, $controller, $action);
            //Fpt_Plugin_Block::processBlockMvc('1002572', $module, $controller, $action);

            //Get layout
            $layoutName = Fpt_Plugin_Block::getLayouts();
            $layoutName = str_replace('.phtml', '', $layoutName);
            if('matchextend' == $controller){
                $layoutName = 'subpage';
            }
            //Layout setup
            $layoutInstance = Zend_Layout::startMvc(
                    array(
                    'layout' => (!empty($layoutName))?$layoutName:'default',
                    'layoutPath' => APPLICATION_PATH . '/layouts/scripts/',
                    'contentKey' => 'content'
                    )
            );

            //Get current view
            $viewInstance = $layoutInstance->getView();

            //Add view phtml
            $viewInstance->addHelperPath(APPLICATION_PATH . '/layouts/helpers');

            //Get application configuration
            $configuration = Fpt_Global::getApplicationIni();

            //set URL to config View
            $viewInstance->config = $configuration['app'];
            $viewInstance->imageSize = $configuration['images'];
            $viewInstance->userid = $session->userid;
            $viewInstance->user = $session->user;

			$viewInstance->controller = $this->_request->getParam('controller');
            $viewInstance->categoryID = $this->_request->getParam('cateid', 0);
            $viewInstance->parentCategoryID = $this->_request->getParam('pcateid', 0);

            // Load data for top menu
            $viewInstance->arrMenu = Category::getInstance()->getMenu();

            if(!empty($layoutName))
            {
                //Execute all sections in layout
                Fpt_Plugin_Block::processSections();
            }

            // Meta refesh
            if(!in_array($controller, array('video')))
            {
                $viewInstance->headMeta()->appendHttpEquiv('REFRESH','1800');
            }
        }//end if
    }

    /**
     * Called before an action is dispatched by the dispatcher.
     * This callback allows for proxy or filter behavior.
     * By altering the request and resetting its dispatched flag
     * via Zend_Controller_Request_Abstract::setDispatched(false),
     * the current action may be skipped and/or replaced.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {

    }

    /**
     * Called after an action is dispatched by the dispatcher.
     * This callback allows for proxy or filter behavior.
     * By altering the request and resetting its dispatched flag
     * via Zend_Controller_Request_Abstract::setDispatched(false)),
     * a new action may be specified for dispatching.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {

    }

    /**
     * Called after Zend_Controller_Front exits its dispatch loop.
     */
    public function dispatchLoopShutdown()
    {
        $configuration = Fpt_Global::getApplicationIni();
        // Only cache if allow
        if (CACHING_PAGE==1)
        {
            $caching = Fpt_Caching_Page::getInstance();
            $caching->write(array(
                    'url'       => str_replace("?".$_SERVER["QUERY_STRING"], "", $_SERVER["REQUEST_URI"]),
                    'cacheDir'  => $configuration['cache']['dir'],
                    'content'   => $this->getResponse()
            ));
        }
        //Check debug
        if ($this->debug)
        {
            //Get application configuration
            $configuration = $configuration['memcache'][ZONE_ENV]['sport'][0];

            //Check towlevels
            $arrConfiguration = array();
            if (strtolower($configuration['adapter']) == 'twolevels')
            {
                $arrConfiguration[] = $configuration[$configuration['adapter']]['fast_backend']['profiler'];
                $arrConfiguration[] = $configuration[$configuration['adapter']]['slow_backend']['profiler'];
            }
            else
            {
                $arrConfiguration[] = $configuration['profiler'];
            }

            //Loop to get data
            $stringAppend = '';
            foreach ($arrConfiguration as $profilerConfiguration)
            {
                //Get profiler
                $profiler = Fpt_Cache_Profiler::getInstance($profilerConfiguration);

                //Add body
                $stringAppend .= $profiler->getProfilerData();
            }

            //Append body
            $this->getResponse()->appendBody($stringAppend);
        }

        //Check xhp
        if ($this->xhp)
        {
            //Get debug data xhprof
            $xhprof_data = xhprof_disable();
            $stringAppend = Fpt_Utility::getXhp($xhprof_data);

            //Append body
            $this->getResponse()->appendBody($stringAppend);
        }
    }
}